<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.merchant_name" placeholder="商户名称/收款人" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <!-- <el-select v-model="listQuery.province" placeholder="请选择省" filterable class="filter-item" style="width: 130px;" @change="changeRegionProvince">
        <el-option v-for="(province,index) in this.merchant_province" :label="province.name" :value="province.region_id"
          :key="index" />
      </el-select>
      <el-select v-model="listQuery.city" placeholder="请选择市"  style="width: 130px;" filterable class="filter-item" @change="changeRegionCity">
        <el-option v-for="(city,index) in this.merchant_city" :label="city.name" :value="city.region_id" :key="index" />
      </el-select>
      <el-select v-model="listQuery.district" placeholder="请选择区县" filterable style="width: 130px;" class="filter-item">
        <el-option v-for="(district,index) in this.merchant_district" :label="district.name" :value="district.region_id"
          :key="index" />
      </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <!-- <el-button v-waves class="filter-item" type="primary" icon="el-icon-search"  @click="excelout">导出</el-button> -->

    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" size="mini"  border fit highlight-current-row style="width: 100%;">
    
      

      <el-table-column label="商户名称" align="center"  width="400px">
        <template slot-scope="{row}">
          <span>{{ row.merchant_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="统一社会信用代码" align="center"  width="180px">
        <template slot-scope="{row}">
          <span>{{ row.merchant_code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" >
        <template slot-scope="{row}">
          <span>{{ row.merchant_address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="法人" align="center"  width="80px">
        <template slot-scope="{row}">
          <span>{{ row.law_person_name }}</span>
        </template>
      </el-table-column>

     
      <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-dropdown-item>
                <el-button type="primary" size="mini" @click="handleDetail(row)">
                  详情
                </el-button>
              </el-dropdown-item>
        </template>

      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :visible.sync="dialogCreateVisible" title="创建商户">
      <el-form ref="dataCheckForm" :rules="merchant_rule" :model="merchant_form" label-position="left" label-width="200px" style="width: 80%; margin-left:70px;">
        <el-form-item label="营业执照" prop="business_license">
          <!-- <el-upload
              :action="UploadUrl()"
              list-type="picture-card"
              :headers="myHeaders"
              :on-success="handSuccess"
              :before-upload="beforeAvatarUpload"
              :on-preview="handlePictureCardPreview"
              :show-file-list="true"
              :data="{field:'business_license'}"
              :file-list="business_license"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload> -->
            <el-upload
              class="avatar-uploader"
              :headers="myHeaders"
              :action="UploadUrl()"
              :show-file-list="false"
              :on-success="handSuccess"
              :data="{field:'business_license',is_read:1}"
              :before-upload="beforeAvatarUpload">
              <img v-if="merchant_form_img.business_license" :src="merchant_form_img.business_license" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="商户名称" prop="merchant_name">
          <el-input v-model="merchant_form.biz.Name" type="text" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="merchant_code" >
          <el-input v-model="merchant_form.biz.RegNum" type="text" placeholder="请输入统一社会信用代码" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogCheckVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleCreateSubmit">确认</el-button>
      </span>
    </el-dialog>
   
  </div>
</template>

<script>
  import {
    fetchMerchantBase,
    handleCreateSubmit,
    getMerchantBaseList,
    
  } from '@/api/merchant'
  import excel from '@/components/excelout/index.vue'
  import waves from '@/directive/waves' // waves directive
  import {
    getNodes
  } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'ComplexTable',
    components: {
      Pagination,excel
    },
    directives: {
      waves
    },
  
    data() {
      return {
        merchant_form:{
          business_license:[],
          merchant_name:'',
          merchant_code:'',
          biz:{
            Name:'',
            RegNum:''
          }
        },
        merchant_form_img:{
          business_license:''
        },
        business_license:[],
        action: process.env.VUE_APP_BASE_API + '/backend_upload',
        myHeaders: {
          token: this.$store.getters.token
        },
        tableKey:1,
        list:[],
        total:0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          merchant_name: '',
          merchant_id: '',
          province: '',
          city: '',
          district: ''
        },
        dialogCreateVisible:false,
        merchant_rule: {
          merchant_name: [{
            required: true,
            message: '商户名称必填',
            trigger: 'blur'
          }],
          merchant_code: [{
            required: true,
            message: '统一社会信用代码必填',
            trigger: 'blur'
          }]
        },
        downloadLoading: false
      }
    },
    created() {
      
      this.listQuery.merchant_id = this.$route.params.merchant_id
      this.cacheQueryFormat();
      this.getList();
      this.nodes = getNodes();
      //添加钩子，页面刷新
      window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    destroyed() {
      //添加钩子，页面刷新
      window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    methods: {
      UploadUrl: function() {
        return this.action
      },
      cacheQueryFormat(){
        let cacheQuery = sessionStorage.getItem('merchantList');
        if(cacheQuery){
          this.listQuery = JSON.parse(cacheQuery);
        }
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleCreate() {
        this.dialogCreateVisible = true
      },
      handleDetail(row){
        this.$router.push('/merchant/merchantBaseDetail/' + row.id)
      },
      handleCreateSubmit(){
        handleCreateSubmit(this.merchant_form).then(res => {
          if(res.code==200){
            this.$notify({
                title: '提示',
                message: res.msg,
                type: 'success',
                duration: 2000,
                onclose: this.getList()
              })
              this.dialogCreateVisible = false;
              this.merchant_form = {};
          }else{
            this.$notify({
                title: '提示',
                message: res.msg,
                type: 'error',
                duration: 2000,

              })
          }
          this.getList()
        })
      },
      beforeAvatarUpload(file) {
        // console.log(file)
        let isJPG = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 200
        if ((file.type === 'image/png') || (file.type === 'image/jpeg') || (file.type === 'image/gif')) {
          isJPG = true
        } else {
          isJPG = false
          this.$message.error('上传头像图片只能是 png,jpg,或者jif格式')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        //  console.log(isJPG && isLt2M)
        return isJPG && isLt2M
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handSuccess(res, file) {
        if(res.code==0){
          this.$notify({
              title: '提示',
              message: res.msg,
              type: 'error',
              duration: 2000,
            })
        }else{
          //this.merchant_form[res.data.field].push(res.data)
          this.merchant_form[res.data.field] = res.data.attach_id.id;
          this.merchant_form_img[res.data.field] = res.data.path
          this.merchant_form.biz = res.data.biz;
        }
       
      },
      handleRemove(file, fileList) {
        this.contractFile[file.field].splice(file["number"], 1);
        this.contract[file.field].splice(file["number"], 1)
      },
      getList() {
        sessionStorage.setItem('merchantList',JSON.stringify(this.listQuery))
        // getMerchantBaseList().then(res => {
        //   this.merchant_type = res.data.type
        //   this.merchant_level = res.data.merchant_level
        //   this.merchant_province = res.data.province
        //   this.level_list = res.data.level_list
        // })
        this.listLoading = true
        getMerchantBaseList(this.listQuery).then(response => {
          this.list = response.data.data
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 1.0 * 1000)
        })
      },
     
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    white-space: nowrap;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    float: left;
  }
</style>
